#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
import threading

def receive_messages(client_socket):
    """接收来自服务器的消息"""
    while True:
        try:
            message = client_socket.recv(1024).decode('utf-8')
            if message:
                print(message)
        except:
            print("[ERROR] Failed to receive message.")
            break

def send_messages(client_socket):
    """发送消息到服务器"""
    while True:
        try:
            message = input()
            if message:
                client_socket.send(message.encode('utf-8'))
        except:
            print("[ERROR] Failed to send message.")
            break

def start_client():
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_ip = "127.0.0.1"  # 本地服务器地址
    server_port = 12345

    try:
        client.connect((server_ip, server_port))
    except:
        print("[ERROR] Could not connect to server.")
        return

    print("[CONNECTED] Connected to server.")

    receive_thread = threading.Thread(target=receive_messages, args=(client,))
    send_thread = threading.Thread(target=send_messages, args=(client,))

    receive_thread.start()
    send_thread.start()

if __name__ == "__main__":
    start_client()
